<?php

namespace App\Http\Api\Services;

use App\Exceptions\InvalidRequestException;
use App\Http\Models\Sms;
use App\Http\Services\BaseService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;


class SmsService extends BaseService
{

    /*
     * 短信采集
     * */
    public function store($attributes = [])
    {
        if(!$attributes){
            return false;
        }

        $tmp_str = array_keys($attributes)[0];

        //接收方 电话号码
        $pattern = '/\"phonum\"\:\"\d+\"/';
        $phonum = $this->getTargetStr($pattern,$tmp_str);

        //短信内容
        $pattern = '/\"msg\"\:\"[\S|\s]+/';
        $msg = $this->getTargetStr($pattern,$tmp_str);

        $msg = base64_decode($msg);
        $msg = mb_convert_encoding($msg, "UTF-8","gb2312");

        $msg = preg_replace('# #','',$msg);

        //发送时间特殊处理
        $time = '';
        $pattern = '/\"time\"\:\"\S*\"/U';
        preg_match_all($pattern,$tmp_str,$res);
        if(!empty($res[0][0])){
            $str = $res[0][0];
            $target = explode(':',$str);
            $time = $target[1].':'.$target[2].':'.$target[3];

            $pattern = ['/\"/','/\_/'];
            $replacement = ['',' '];
            $time = preg_replace($pattern,$replacement,$time);

        }

        //发送方电话
        $pattern = '/\"phone\"\:\"\d+\"/';
        $phone = $this->getTargetStr($pattern,$tmp_str);

        if($phone && $phonum && $msg && $time){
            $data = [
                'phone' => $phone,
                'phonum' => $phonum,
                'msg' => $msg,
                'time' => $time,
            ];
            Sms::create($data);
            Log::info('通');
            if(strpos($phonum,'0054') !== false || $phonum == '13514058767'){
                Log::info('过');
                $token = '9995caf66b5c4c6f9038f226c39c1e20129a784c59e76c9b403b9ef2fe3c89ee';
                (new \App\Lib\DingDingNotice\Sms($phonum,$phone,$msg,$time,$token))->sendMarkdownMessage();
            }else{
                //钉钉通知
                $token = '199aefa1deb87e361de3d18904a6366eb09fada4397a9230933a1ab4068a4bd8';
                (new \App\Lib\DingDingNotice\Sms($phonum,$phone,$msg,$time,$token))->sendMarkdownMessage();
            }


        }

        return true;


    }

    public function getTargetStr($pattern,$subject){

        preg_match_all($pattern,$subject,$res);

        if(!empty($res[0][0])){
            $str = $res[0][0];
            $target = explode(':',$str)[1];
            $pattern = ['/\"/','/\\n/','/\_/'];
            $replacement = ['','','+'];
            $result = preg_replace($pattern,$replacement,$target);
            return $result;
        }
        return null;
    }




}
